package com.system.boot.rbac.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.system.api.rbac.entity.po.SysRolePermissionRelation;
import com.system.boot.rbac.mapper.RolePermissionRelationMapper;
import com.system.boot.rbac.service.RolePermissionService;
import com.system.common.constant.SystemConstant;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.yang.common.core.exception.BaseException;
import org.yang.common.utils.jwt.JwtTokenAnalysisUtli;

import java.util.*;

/**
 *  
 * @author: lslands
 * @description:   
 * @version：v1.0
 * @date:    2024/6/28 22:47
 */
@Service
public class RolePermissionServiceImpl extends ServiceImpl<RolePermissionRelationMapper, SysRolePermissionRelation> implements RolePermissionService {


    @Override
    public List<Long> getPermissionsByRole(Long roleId) throws BaseException {
        return baseMapper.selectPermsByRole(roleId);
    }
    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public boolean assignPermission(Long roleId, List<Long> permissionIds) throws BaseException {
        List<SysRolePermissionRelation> relations = baseMapper
                .selectList(new LambdaQueryWrapper<SysRolePermissionRelation>().select(SysRolePermissionRelation::getPermissionId)
                        .eq(SysRolePermissionRelation::getRoleId, roleId));
        if(relations.isEmpty()){
            List<SysRolePermissionRelation> list = permissionIds.stream().map(x -> new SysRolePermissionRelation(roleId, x)).toList();
            return this.saveBatch(list);
        }
        List<Long> permIds = relations.stream().map(SysRolePermissionRelation::getPermissionId).toList();
        //获取差集 -需要删除
        List<Long> deleteIds = CollectionUtils.subtract(permIds,permissionIds).stream().toList();
        if(!deleteIds.isEmpty()){
            baseMapper.deletePermIdsByBatch(deleteIds, String.valueOf(JwtTokenAnalysisUtli.useId()));
        }
        Set<Long> complementSet = new HashSet<>(permissionIds);
        permIds.forEach(complementSet::remove);
        System.out.println(complementSet);
        if(!complementSet.isEmpty()){
            List<SysRolePermissionRelation> list = complementSet.stream()
                    .map(x -> new SysRolePermissionRelation(roleId, x)).toList();
           return this.saveBatch(list);
        }
        return true;
    }

    public static void main(String[] args) {
        List<Integer> list = List.of(1,8,9,10);
        List<Integer> listNew = List.of(9,10);
        System.out.println("差集："+CollectionUtils.subtract(list,listNew).stream().toList());
        System.out.println("补集："+CollectionUtils.disjunction(list,listNew));
    }
}

